package org.hwadee.service;

import org.hwadee.entity.Communication;
import org.hwadee.entity.Message;
import org.hwadee.mapper.MessageMapper;
import org.hwadee.webSocket.WebSocket;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class MessageService {

    @Autowired
    private MessageMapper messageMapper;
    @Autowired
    private CommunicationService communicationService;

    public Message getMessageById(Integer messageId) {
        return messageMapper.getMessageById(messageId);
    }

    public List<Message> getMessageByReceiverId(Integer receiverId) {
        return messageMapper.getMessageByReceiverId(receiverId);
    }

    public List<Message> getMessageBySenderId(Integer senderId) {
        return messageMapper.getMessageBySenderId(senderId);
    }

    public Message getNewestMessageByUserId(Integer userIdA, Integer userIdB) {
        return messageMapper.getNewestMessageByUserId(userIdA, userIdB);
    }

    public void sendMessage(Integer userId, int receiverId, String context) {
        if(communicationService.selectCommunicationBySenderAndReceiverId(userId, receiverId) == null) {
            Communication communication1 = new Communication();
            Communication communication2 = new Communication();
            communication1.setSender(userId);
            communication1.setReceiver(receiverId);
            communication2.setSender(receiverId);
            communication2.setReceiver(userId);
            communication1.setLastMessageTime(new Date());
            communication2.setLastMessageTime(new Date());
            communicationService.insertCommunication(communication1);
            communicationService.insertCommunication(communication2);
        }
        Message message = new Message();
        message.setSender(userId);
        message.setReceiver(receiverId);
        message.setSendTime(new Date());
        message.setMessageContent(context);
        messageMapper.insertMessage(message);
    }

    public List<Message> listmessagesByUserId(Integer userIdA, Integer userIdB) {
        return messageMapper.listMessagesByUserId(userIdA,userIdB);
    }
}
